<?php

class SiteController extends Controller {

    /**
     * Declares class-based actions.
     */
    public function actions() {
        return array(
            // captcha action renders the CAPTCHA image displayed on the contact page
            'captcha' => array(
                'class' => 'CCaptchaAction',
                'backColor' => 0xFFFFFF,
            ),
            // page action renders "static" pages stored under 'protected/views/site/pages'
            // They can be accessed via: index.php?r=site/page&view=FileName
            'page' => array(
                'class' => 'CViewAction',
            ),
        );
    }

    public function actionChangeLanguage() {
        $lang = Yii::app()->request->getParam('lang');
        Yii::app()->session['language'] = $lang;

        $redirect = Yii::app()->request->getParam('redirect');
        Yii::app()->request->redirect(CHtml::decode($redirect));
    }

    /**
     * This is the default 'index' action that is invoked
     * when an action is not explicitly requested by users.
     */
    public function actionIndex() {
        $this->layout = '//layouts/column3';
        $data = array();
        $postModel = new Post();
        $post = $postModel->findAboutPost(true);
        if (count($post) > 0) {
            $data['about'] = $post;
        }
        
        // render 'index' view
        $this->render('index', $data);
    }

    /**
     * This is the action to handle external exceptions.
     */
    public function actionError() {
        if ($error = Yii::app()->errorHandler->error) {
            if (Yii::app()->request->isAjaxRequest)
                echo $error['message'];
            else
                $this->render('error', $error);
        }
    }

    /**
     * send mail with phpmailer
     */
    public function sendPhpMailer($info = array()) {
        require("protected/extensions/phpmailer/class.phpmailer.php");
        $mail = new PHPMailer();
        $mail->IsSMTP(); // send via SMTP
        //IsSMTP(); // send via SMTP
        $mail->SMTPAuth = true; // turn on SMTP authentication
        $mail->Username = "ktpmhk12011@gmail.com"; // SMTP username
        $mail->Password = "ktpm2011"; // SMTP password
        $webmaster_email = "ktpmhk12011@gmail.com"; //Reply to this email ID     
        $mail->From = $webmaster_email;
        $mail->FromName = "Webmaster";

        $emailTo = $info['emailTo']; // Recipients email ID
        $name = "Webmaster"; // Recipient's name
        $mail->AddAddress($emailTo, $name);
        $mail->AddReplyTo($webmaster_email, "Webmaster");
        $mail->WordWrap = 50; // set word wrap
        //$mail->AddAttachment("/var/tmp/file.tar.gz"); // attachment
        // $mail->AddAttachment("/tmp/image.jpg", "new.jpg"); // attachment

        $mail->IsHTML(true); // send as HTML
        $mail->Subject = $info['subject'];
        $mail->Body = $info['body']; //HTML Body
        // $mail->AltBody = "This is the body when user views in plain text format"; //Text Body
        if (!$mail->Send()) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * get email admin
     * @var $user CActiveRecord
     */
    public function getAdminEmail() {
        $email = '';
        try {
            $criteria = new CDbCriteria;
            $criteria->condition = 'username=:username';
            $criteria->params = array(':username' => 'admin');
            $user = User::model()->find($criteria);
            $email = $user->email;
        } catch (Exception $ex) {
            
        }
        return $email;
    }

    /**
     * Displays the contact page
     */
    public function actionContact() {
        $contactForm = new ContactForm;

        if (isset($_POST['ContactForm'])) {
            $contactForm->attributes = $_POST['ContactForm'];
            if ($contactForm->validate()) {
                $info = array();
                $info['emailTo'] = $this->getAdminEmail();
                $info['subject'] = $contactForm->subject;
                //$info['body'] = 'Tên khách hàng:' . $contactForm->name . '\n' . 'Email:' . $contactForm->email . '\n' . $contactForm->body;
                $info['body'] = '<div>
                                    <h4>Tên khách hàng:' . $contactForm->name . '</h4>
                                    <h4>Email: ' . $contactForm->email . '</h4>
                                    <p>' . $contactForm->body . '</p>
                                 <div>';
                $this->sendPhpMailer($info);
                Yii::app()->user->setFlash('contact', Yii::t('contact', 'successContact'));
                $this->refresh();
            }
        }

        $this->breadcrumbs[] = Yii::t('default', 'Contact');
        $this->pageTitle = Yii::t('default', 'Contact');

        $this->render('contact', array(
            'model' => $contactForm,
        ));
    }

    /**
     * Render 'about' page
     */
    public function actionAbout() {
        // create creteira object
        $criteria = new CDbCriteria;
        $criteria->with = array('postDetails' => array(),
            'postImages' => array());
        $criteria->addCondition(array('postDetails.language = :language',
            'postDetails.title = :title'));
        $criteria->params = array(':language' => Yii::app()->language,
            ':title' => '_about_');

        $results = Post::model()->findAll($criteria);
        if ($results == null || count($results) == 0) {
            return;
        }

        $post = $results[0];

        $postDetail = $post->getPostDetail(Yii::app()->language);
        $postDetail->title = Yii::t('default', 'About Us');
        $postImages = count($post->postImages) > 0 ? $post->postImages : array();

        $this->breadcrumbs[] = Yii::t('default', 'About Us');
        $this->pageTitle = Yii::t('default', 'About Us');

        // render view page
        $this->render('application.views.post.view', array(
            'post' => $post,
            'postDetail' => $postDetail,
            'postImages' => $postImages,
        ));
    }

    /**
     * Render 'support' page
     */
    public function actionSupport($type) {
        $this->layout = '//layouts/column5';
        $title;
        $actualTitle;
        if ($type == 'purchase') {
            $title = '_support_purchase_method_';
            $this->pageTitle = Yii::t('default', 'Purchase method');
            $this->breadcrumbs[] = Yii::t('default', 'Purchase method');
            $actualTitle = Yii::t('default', 'Purchase method');
        } else if ($type == 'payment') {
            $title = '_support_payment_methods_';
            $this->pageTitle = Yii::t('default', 'Payment methods');
            $this->breadcrumbs[] = Yii::t('default', 'Payment methods');
            $actualTitle = Yii::t('default', 'Payment methods');
        } else {
            
        }
        $post = Post::model()->getPostByTitle($title);
        $postDetail = $post->postDetail();
        $postDetail->title = $actualTitle;
        $postImages = count($post->postImages) > 0 ? $post->postImages : array();

        // render view page
        $this->render('application.views.post.view', array(
            'post' => $post,
            'postDetail' => $postDetail,
            'postImages' => $postImages,
        ));
    }

    /**
     * Render 'policy' page
     */
    public function actionPolicy($type) {
        $this->layout = '//layouts/column5';
        $title;
        $actualTitle;
        if ($type == 'warranty') {
            $title = '_policy_product_warranty_';
            $this->pageTitle = Yii::t('default', 'Product warranty');
            $this->breadcrumbs[] = Yii::t('default', 'Product warranty');
            $actualTitle = Yii::t('default', 'Product warranty');
        } else if ($type == 'returns') {
            $title = '_policy_product_returns_';
            $this->pageTitle = Yii::t('default', 'Product returns');
            $this->breadcrumbs[] = Yii::t('default', 'Product returns');
            $actualTitle = Yii::t('default', 'Product returns');
        } else {
            $title = ' _policy_delivery_';
            $this->pageTitle = Yii::t('default', 'Time and mode of delivery');
            $this->breadcrumbs[] = Yii::t('default', 'Time and mode of delivery');
            $actualTitle = Yii::t('default', 'Time and mode of delivery');
        }
        $post = Post::model()->getPostByTitle($title);
        $postDetail = $post->postDetail();
        $postDetail->title = $actualTitle;
        $postImages = count($post->postImages) > 0 ? $post->postImages : array();

        // render view page
        $this->render('application.views.post.view', array(
            'post' => $post,
            'postDetail' => $postDetail,
            'postImages' => $postImages,
        ));
    }

    /**
     * Displays the login page
     */
    public function actionLogin() {
        $model = new User;

        // if it is ajax validation request
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'login-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }

        $name1 = Yii::app()->user->name;
        // collect user input data
        if (isset($_POST['User'])) {
            $model->attributes = $_POST['User'];
            // validate user input and redirect to the previous page if valid
            $result = $model->login();
            if ($result) {
                $role = $result->role;
                if($role == 'admin') {
                    $this->redirect(Yii::app()->request->baseUrl . '/admin/product');
                }
                $this->redirect(Yii::app()->request->baseUrl. '/');
            } else {
                Yii::app()->user->setFlash('message-login', Yii::t('default', 'User name or pass is incorrect'));
            }
        }

        $this->pageTitle = Yii::t('default', 'Login');

        // display the login form
        $this->render('login', array('model' => $model));
    }

    /**
     * Logs out the current user and redirect to homepage.
     */
    public function actionLogout() {
        Yii::app()->user->logout();
        $this->redirect(Yii::app()->homeUrl);
    }

    /**
     * Displays the register page
     */
    public function actionRegister() {
        $register = new User;

        if (isset($_POST['User'])) {
            $register->attributes = $_POST['User'];
            if ($register->validate()) {
                $register->save();
                Yii::app()->user->setFlash('register', Yii::t('default', 'Register successfully'));
                $this->refresh();
            }
        }

        $this->breadcrumbs[] = Yii::t('default', 'Register');
        $this->pageTitle = Yii::t('default', 'Register');

        $this->render('register', array(
            'model' => $register,
        ));
    }

}